package io.wit.modules.api;

import cloud.dwz.service.SysAreaService;
import io.wit.common.exception.RRException;
import io.wit.common.utils.JsonUtils;
import io.wit.common.utils.R;
import io.wit.common.weixin.WeiXinUtil;
import io.wit.modules.oss.entity.SysOssEntity;
import io.wit.modules.oss.service.SysOssService;
import io.wit.modules.sys.dao.SysUserDao;
import io.wit.modules.sys.entity.SysDeptEntity;
import io.wit.modules.sys.entity.SysItemEntity;
import io.wit.modules.sys.entity.SysUserEntity;
import io.wit.modules.sys.service.SysDeptService;
import io.wit.modules.sys.service.SysItemService;
import io.wit.modules.sys.service.SysUserService;
import io.wit.modules.sys.shiro.ShiroUtils;
import io.wit.modules.wit.entity.CashierEntity;
import io.wit.modules.wit.entity.DynamicEntity;
import io.wit.modules.wit.entity.EmployeeEntity;
import io.wit.modules.wit.entity.FarmEntity;
import io.wit.modules.wit.entity.FarmingEntity;
import io.wit.modules.wit.entity.IntegralEntity;
import io.wit.modules.wit.entity.MarketEntity;
import io.wit.modules.wit.entity.NoticeEntity;
import io.wit.modules.wit.entity.SubjectEntity;
import io.wit.modules.wit.entity.UserEntity;
import io.wit.modules.wit.entity.WorkingEntity;
import io.wit.modules.wit.service.CashierService;
import io.wit.modules.wit.service.DynamicService;
import io.wit.modules.wit.service.EmployeeService;
import io.wit.modules.wit.service.FarmService;
import io.wit.modules.wit.service.FarmingService;
import io.wit.modules.wit.service.IntegralService;
import io.wit.modules.wit.service.MarketService;
import io.wit.modules.wit.service.NoticeService;
import io.wit.modules.wit.service.SubjectService;
import io.wit.modules.wit.service.WorkingService;
import io.wit.tool.ToolClient;
import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("witApi")
public class witApiController {

    @Autowired
    private WeiXinUtil weiXinUtil;
	@Autowired
    private SysUserDao sysUserDao;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private DynamicService dynamicService;
	@Autowired
	private SysOssService sysOssService;
	@Autowired
	private FarmService farmService;
	@Autowired
	private SysItemService SysItemService;
	@Autowired
	private EmployeeService employeeService;
	@Autowired
	private FarmingService farmingService;
	@Autowired
	private WorkingService workingService;
	@Autowired
	private CashierService cashierService;
	@Autowired
	private MarketService marketService;
	@Autowired
	private SubjectService subjectService;
	@Autowired
	private IntegralService integralService;
	@Autowired
	private NoticeService noticeService;
	@Autowired
	private SysDeptService sysDeptService;
    @Autowired
    private SysAreaService sysAreaService;
	//增加日志
    private static Logger log = LoggerFactory.getLogger(witApiController.class);

    //验证是否来自微信服务器的消息
    @RequestMapping(value = "",method = RequestMethod.GET)
    public String checkSignature(@RequestParam(name = "signature" ,required = false) String signature  ,
                                 @RequestParam(name = "nonce",required = false) String  nonce ,
                                 @RequestParam(name = "timestamp",required = false) String  timestamp ,
                                 @RequestParam(name = "echostr",required = false) String  echostr){
        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        if (weiXinUtil.checkSignature(signature, timestamp, nonce)) {
            log.info("接入成功");
            return echostr;
        }
        log.error("接入失败");
        return "";
    }

    @RequestMapping(value = "/AccessToken",method = RequestMethod.GET)
    public String AccessToken(){
    	String access_token = weiXinUtil.getAccess_Token();  
        return "调用成功access_token:"+access_token;
    }

    @RequestMapping(value = "/ApiTicket",method = RequestMethod.GET)
    public String ApiTicket() throws Exception {
    	String api_ticket = weiXinUtil.getJsApi_Ticket();  
        return "调用成功api_ticket:"+api_ticket;
    }

    @RequestMapping(value = "/signature",method = RequestMethod.GET)
    public Map<String, String> signature(@RequestParam String url) throws Exception {
    	Map<String, String> ret = new HashMap<String, String>();
    	String noncestr=UUID.randomUUID().toString();
		String timestamp=Long.toString(System.currentTimeMillis() / 1000);
		String ticket_api = weiXinUtil.getJsApi_Ticket();
		String str = "jsapi_ticket=" + ticket_api + "&noncestr=" + noncestr + "&timestamp=" + timestamp +  "&url=" + url;
		String signature =weiXinUtil.SHA1(str);
		ret.put("url", url);
        ret.put("jsapi_ticket", ticket_api);
        ret.put("nonceStr", noncestr);
        ret.put("timestamp", timestamp);  
        ret.put("signature", signature);
        ret.put("appid", weiXinUtil.getAPPID());
        return ret;  
    }

    @PostMapping(value = "/login")
    public Map<String,Object> login(String username, String password){
    	final Map<String,Object> map = new HashMap<String,Object>();
    	final UserEntity user = sysUserDao.queryObjects(username);
    	if(user == null){
            map.put("code",199);
            map.put("msg","用户名或密码错误!");
            return map;
        }
        if(!user.getPassword().equals(ShiroUtils.sha256(password,user.getSalt()))){
            map.put("code",199);
            map.put("msg","用户名或密码错误!");
            return map;
        }
        final int status = user.getStatus();
        if(status == 0){
            map.put("code",199);
            map.put("msg","您的账号已被禁用");
            return map;
        }
        if(status == 2){
            map.put("code",199);
            map.put("msg","请联系管理员审核你账号");
            return map;
        }
        if(user.getPassword().equals(ShiroUtils.sha256(password,user.getSalt())) && status == 1){
            map.put("code",200);
            map.put("msg","登陆成功");
            map.put("type",user.getType().toString());
            map.put("status",user.getStatus().toString());
            map.put("userId",user.getUserId().toString());
            map.put("userName",user.getUserName());
            map.put("roleId",user.getRoleId());
            map.put("identify",Boolean.valueOf(user.getIdentify()));
            map.put("roleName",user.getRoleName());
            map.put("deptId",user.getDeptId());
            final Long subjectId = user.getSubjectId();
            if(subjectId != null){
                map.put("subjectId",String.valueOf(user.getSubjectId()));
                map.put("subjectName",user.getSubjectName());
            }
            if(user.getIntegral() == null){
                map.put("integral","0");
            }else{
                map.put("integral",String.valueOf(user.getIntegral()));
            }
            return map;
        }else{
            map.put("code",199);
            map.put("msg","用户名或密码错误");
            return map;
        }
    }

    /**
     * 注册 http://127.0.0.1/witApi/register?mobile?13765121695&password=123456
     * @param user
     * @return
    */
    @RequestMapping(value="/register")
    public Map<String,Object> register(@RequestBody SysUserEntity user) {
    	final Map<String,Object> ret = new HashMap<String,Object>();
    	final UserEntity userEntity = sysUserDao.queryObjects(user.getMobile());
    	if (userEntity != null) {
    		ret.put("code",199);
        	ret.put("msg","该手机号已经注册,请登陆");
        	return ret;
    	}
    	user.setUsername(user.getMobile());
    	user.setType(1);//微信公众号注册默认为 经营主体
    	user.setStatus(2);//待审核
    	//user.setDeptId((long)1);//该字段已废弃,因为默认怎么一开始注册就有部门???
    	user.setRoleId((long)1);//手机端注册默认角色为'经营主体角色'
    	sysUserService.save(user);
    	final UserEntity users = sysUserDao.queryObjects(user.getUsername());
		if (users.getUserId() != null) {
    		ret.put("code",200);
        	ret.put("msg","注册成功");
        	ret.put("type",users.getType());
        	ret.put("userId",users.getUserId());
        	ret.put("userName",users.getUserName());
        	ret.put("roleId",users.getRoleId());
        	ret.put("roleName",users.getRoleName());
        	ret.put("identify",Boolean.valueOf(users.getIdentify()));
        	ret.put("integral","0");
        	ret.put("county",users.getCounty());
    	}else {
    		ret.put("code",199);
        	ret.put("msg","注册失败");
    	}
    	return ret;
    }

    @RequestMapping("/home")
    public R home(Long subjectId) {
    	final NoticeEntity notice = noticeService.queryObjects();
    	List<FarmEntity> farm = farmService.farmLists(subjectId);
		List<IntegralEntity> integral = integralService.integralList();
    	JsonUtils json=new JsonUtils(notice,farm,integral);
    	return R.ok().put("data", json);
    }

    /**
	 * 上传文件
	*/
	@RequestMapping("/uploadWx")
	public R uploadWx(String serverId) throws Exception {
		if (serverId.isEmpty()) {
			throw new RRException("上传文件不能为空");
		}
		//上传文件
		String url = weiXinUtil.downloadMedia(serverId);
		//保存文件信息
		SysOssEntity ossEntity = new SysOssEntity();
		ossEntity.setUrl(url);
		ossEntity.setCreateDate(new Date());
		sysOssService.save(ossEntity);
		return R.ok().put("url", url);
	}

	@RequestMapping("/getSelect")
	public R getSelect(Long subjectId) {
		final List<FarmEntity> farmList = farmService.farmList(subjectId);
		return R.ok().put("itemList", farmList);
	}

	@RequestMapping("/getItem")
	public R getItem(Long itemId) {
		List<SysItemEntity> itemList = SysItemService.queryItemList(itemId);
		return R.ok().put("itemList", itemList);
	}

	//获取计量单位
	@RequestMapping("/getUint")
	public R getUint() {
		List<SysItemEntity> itemList = SysItemService.getUint();
		return R.ok().put("itemList", itemList);
	}

	//获取角色类型
	@RequestMapping("/getTypeRoles")
	public R getTypeRoles(final Long subjectId) {
		List<SysItemEntity> itemList = SysItemService.getTypeRoles(subjectId);
		return R.ok().put("itemList", itemList);
	}
	
    /**
	 * 获取动态信息
	*/
	@RequestMapping("/dynamicInfo/{dataId}")
	public R dynamicInfo(@PathVariable("dataId") Long dataId){
		DynamicEntity dynamic = dynamicService.queryObject(dataId);
		return R.ok().put("dynamic", dynamic);
	}

	/**
	 * 保存动态
	*/
	@RequestMapping("/dynamicSave")
	public R dynamicSave(@RequestBody DynamicEntity dynamic){
		dynamicService.save(dynamic);
		return R.ok();
	}

	/**
	 * 修改动态信息
	*/
	@RequestMapping("/dynamicUpdate")
	public R dynamic(@RequestBody DynamicEntity dynamic){
		dynamicService.update(dynamic);
		return R.ok();
	}

	/**
	 * 获取动态列表
	 * @param page
	 * @param limit
	 * @return
	*/
	@RequestMapping("/getDynamiclist")
	public R getDynamic(int page,int limit,Long subjectId) {
		//查询列表数据
		Map<String, Object> query = new HashMap<String, Object>();
		query.put("subjectId", subjectId);
		query.put("offset", (page - 1) * limit);
		query.put("page", page);
		query.put("limit", limit);
		List<DynamicEntity> dynamicList = dynamicService.queryList(query);
		return R.ok().put("list", dynamicList);
	}

	/**
	 * 获取基地信息
	*/
	@RequestMapping("/framInfo/{dataId}")
	public R framInfo(@PathVariable("dataId") Long dataId){
		FarmEntity fram = farmService.queryObject(dataId);
		return R.ok().put("fram", fram);
	}

	/**
	 * 保存基地
	*/
	@RequestMapping("/framSave")
	public R framSave(@RequestBody FarmEntity fram){
		farmService.save(fram);
		return R.ok();
	}

	/**
	 * 修改基地信息
	*/
	@RequestMapping("/framUpdate")
	public R framUpdate(@RequestBody FarmEntity fram){
		farmService.update(fram);
		return R.ok();
	}

	/**
	 * 获取基地列表
	 * @param page
	 * @param limit
	 * @return
	*/
	@RequestMapping("/getFramlist")
	public R getFramlist(int page,int limit,Long subjectId) {
		//查询列表数据
		Map<String, Object> query = new HashMap<String, Object>();
		query.put("subjectId", subjectId);
		query.put("offset", (page - 1) * limit);
		query.put("page", page);
		query.put("limit", limit);
		List<FarmEntity> framList = farmService.queryList(query);
		return R.ok().put("list", framList);
	}

	/**
	 * 信息
	 */
	@RequestMapping("/employeeInfo/{dataId}")
	public R employeeInfo(@PathVariable("dataId") Long dataId){
		EmployeeEntity employee = employeeService.queryObject(dataId);
		return R.ok().put("employee", employee);
	}

	/**
	 * 员工新增
	*/
	@RequestMapping("/employeeSave")
	public R employeeSave(@RequestBody EmployeeEntity employee){
        final Long dataId = employeeService.save(employee);
        final R r = new R();
        r.put("code",0);
        r.put("data",dataId);
        return r;
	}

	@RequestMapping("/accountSave")
	public void accountSave(@RequestBody SysUserEntity user){
		user.setUsername(user.getMobile());
    	user.setType(2);
    	user.setStatus(0);
    	sysUserService.save(user);
	}

	@RequestMapping(value = "/updatePwd",method = RequestMethod.POST)
	public void updatePwd(Long userId,String password){
		SysUserEntity user=new SysUserEntity();
		String salt = RandomStringUtils.randomAlphanumeric(20);
		user.setUserId(userId);
		user.setSalt(salt);
		user.setPassword(ShiroUtils.sha256(password, user.getSalt()));
    	sysUserService.updatePwd(user);
	}

	/**
	 * 修改员工信息
	*/
	@RequestMapping("/employeeUpdate")
	public R employeeUpdate(@RequestBody EmployeeEntity employee){
		employeeService.update(employee);
		return R.ok();
	}

	/**
	 * 获取员工列表
	 * @param page
	 * @param limit
	 * @return
	*/
	@RequestMapping("/getEmployeelist")
	public R getEmployeelist(int page,int limit,Long subjectId) {
		//查询列表数据
		Map<String, Object> query = new HashMap<String, Object>();
		query.put("subjectId", subjectId);
		query.put("offset", (page - 1) * limit);
		query.put("page", page);
		query.put("limit", limit);
		List<EmployeeEntity> employeeList = employeeService.queryList(query);
		return R.ok().put("list", employeeList);
	}

	/**
	 * 农事信息
	*/
	@RequestMapping("/framingInfo/{dataId}")
	public R framingInfo(@PathVariable("dataId") Long dataId){
		FarmingEntity framing = farmingService.queryObject(dataId);
		return R.ok().put("framing", framing);
	}

	/**
	 * 保存农事
	*/
	@RequestMapping("/framingSave")
	public R framingSave(@RequestBody FarmingEntity framing){
		farmingService.save(framing);
		return R.ok();
	}

	/**
	 * 修改农事
	*/
	@RequestMapping("/framingUpdate")
	public R framingUpdate(@RequestBody FarmingEntity farming){
		farmingService.update(farming);
		
		return R.ok();
	}

	/**
	 * 获取农事列表
	 * @param page
	 * @param limit
	 * @return
	*/
	@RequestMapping("/getFraminglist")
	public R getFraminglist(int page,int limit,Long subjectId) {
		//查询列表数据
		Map<String, Object> query = new HashMap<String, Object>();
		query.put("subjectId", subjectId);
		query.put("offset", (page - 1) * limit);
		query.put("page", page);
		query.put("limit", limit);
		List<FarmingEntity> framingList = farmingService.queryList(query);
		return R.ok().put("list", framingList);
	}

	/**
	 * 用工信息
	*/
	@RequestMapping("/workersInfo/{dataId}")
	public R workingInfo(@PathVariable("dataId") Long dataId){
		WorkingEntity working = workingService.queryObject(dataId);
		
		return R.ok().put("workers", working);
	}

	/**
	 * 保存用工
	*/
	@RequestMapping("/workersSave")
	public R workersSave(@RequestBody WorkingEntity workers){
		workingService.save(workers);
		return R.ok();
	}

	/**
	 * 修改用工
	*/
	@RequestMapping("/workersUpdate")
	public R workersUpdate(@RequestBody WorkingEntity working){
		workingService.update(working);
		return R.ok();
	}

	/**
	 * 获取用工列表
	 * @param page
	 * @param limit
	 * @return
	*/
	@RequestMapping("/getWorkerslist")
	public R getWorkerslist(int page,int limit,Long subjectId) {
		//查询列表数据
		Map<String, Object> query = new HashMap<String, Object>();
		query.put("subjectId", subjectId);
		query.put("offset", (page - 1) * limit);
		query.put("page", page);
		query.put("limit", limit);
		List<WorkingEntity> framingList = workingService.queryList(query);
		return R.ok().put("list", framingList);
	}

	/**
	 * 财务列表
	 * @param page
	 * @param limit
	 * @return
	*/
	@RequestMapping("/getCashierlist")
	public R getCashierlist(int page,int limit,int type,String datetime,Long subjectId){
		//查询列表数据
		Map<String, Object> query = new HashMap<String, Object>();
		if(type!=-1) {
			query.put("type", type);
		}
		query.put("subjectId", subjectId);
		query.put("operatordate", datetime);
		query.put("offset", (page - 1) * limit);
		query.put("page", page);
		query.put("limit", limit);
		List<CashierEntity> cashierList = cashierService.queryList(query);
		return R.ok().put("list", cashierList);
	}

	/**
	 * 获取财务信息
	*/
	@RequestMapping("/cashierInfo/{dataId}")
	public R cashierInfo(@PathVariable("dataId") Long dataId){
		CashierEntity cashier = cashierService.queryObject(dataId);
		return R.ok().put("cashier", cashier);
	}
	
	/**
	 * 保存财务信息
	*/
	@RequestMapping("/cashierSave")
	public R cashierSave(@RequestBody CashierEntity cashier){
		cashierService.save(cashier);
		return R.ok();
	}
	
	/**
	 * 修改财务信息
	 */
	@RequestMapping("/cashierUpdate")
	public R cashierUpdate(@RequestBody CashierEntity cashier){
		cashierService.update(cashier);
		
		return R.ok();
	}

	/**
	 * 列表
	*/
	@RequestMapping("/getMarketlist")
	public R list(int page,int limit,String datetime,Long subjectId){
		//查询列表数据
		Map<String, Object> query = new HashMap<String, Object>();
		query.put("subjectId", subjectId);
		query.put("operatordate", datetime);
		query.put("offset", (page - 1) * limit);
		query.put("page", page);
		query.put("limit", limit);
		List<MarketEntity> marketList = marketService.queryList(query);
		return R.ok().put("list", marketList);
	}
	
	/**
	 * 信息
	*/
	@RequestMapping("/marketInfo/{dataId}")
	public R marketInfo(@PathVariable("dataId") Long dataId){
		MarketEntity market = marketService.queryObject(dataId);
		return R.ok().put("market", market);
	}
	
	/**
	 * 保存
	*/
	@RequestMapping("/marketSave")
	public R save(@RequestBody MarketEntity market){
		marketService.save(market);
		return R.ok();
	}
	
	/**
	 * 修改
	*/
	@RequestMapping("/marketUpdate")
	public R update(@RequestBody MarketEntity market){
		marketService.update(market);
		return R.ok();
	}

	/**
	 * 获取经营主体信息
	*/
	@RequestMapping("/subjectInfo/{dataId}")
	public R subjectInfo(@PathVariable("dataId") Long dataId){
		SubjectEntity subject = subjectService.queryObject(dataId);
		return R.ok().put("subject", subject);
	}
	
	/**
	 * 经营主体保存,完善经营主体
	*/
	@RequestMapping("/subjectSave")
	public Map<String,Object> subjectSave(@RequestBody SubjectEntity subject){
		subjectService.save(subject);
		final Map<String,Object> ret = new HashMap<String,Object>();
		final UserEntity users = sysUserDao.queryObjects(subject.getUserName());
    	if (users.getUserId() != null) {
    		ret.put("code",200);
        	ret.put("msg","操作成功");
        	ret.put("status",users.getStatus());
        	ret.put("userId",users.getUserId());
        	ret.put("userName",users.getUserName());
        	ret.put("roleId",users.getRoleId());
        	ret.put("roleName",users.getRoleName());
        	ret.put("type",users.getType());
        	ret.put("subjectId",users.getSubjectId());
        	ret.put("subjectName",users.getSubjectName());
        	ret.put("integral",users.getIntegral());
        	ret.put("county",users.getCounty());
        	ret.put("identify",true);
            //sysUserService.updates(users.getUserId(),users.getSubjectId(),String.valueOf(subject.getCounty()));
    	}else {
    		ret.put("code",199);
        	ret.put("msg","操作失败");
    	}
		return ret;
	}
	
	/**
	 * 经营主体修改
	*/
	@RequestMapping("/subjectUpdate")
	public R subjectUpdate(@RequestBody SubjectEntity subject){
		subjectService.update(subject);
        final R ret = new R();
        ret.put("code",200);
        ret.put("msg","操作成功");
        return ret;
	}

	/**
	 * 保存积分
	*/
	@RequestMapping("/integralSave")
	public R integralSave(@RequestBody IntegralEntity integral){
		integralService.save(integral);
		return R.ok();
	}

	/**
	 * 手机端显示基地
	 * @return
	*/
	@RequestMapping("/getFarm")
	public R getFarm(Long county) {
		List<FarmEntity> farm = farmService.getFarm(county);
		return R.ok().put("farm", farm);
	}

	/**
	 * 手机端显示基地
	 * @return
	*/
	@RequestMapping("/getUserList")
	public R getUserList(Long subjectId) {
		//查询列表数据
		List<EmployeeEntity> userList = employeeService.getUserList(subjectId);
		return R.ok().put("user", userList);
	}

	/**
	 * 获取机构
	 * @return
	*/
	@RequestMapping("/getDept")
	public R getDept(Long dataId) {
		final List<SysDeptEntity> dept = sysDeptService.getDept(dataId);
		return R.ok().put("dept", dept);
	}

    /**获取地区*/
    @GetMapping("/getAreaInfo")
    public void getAreaInfo(final Long pId,final HttpServletResponse response){
        final String json = sysAreaService.getListArea(pId);
        ToolClient.responseJson(json,response);
    }
}